﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace FileClient
{
    public class StateObject
    {
        public Socket workSocket = null;
        public const int BufferSize = 1024 * 99999;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder sb = new StringBuilder();
    }

    public class Config
    {
        public static int IP = 0;

        public static List<string> FileList = new List<string>();
        public static Config DataBase = new Config();
        public static ArrayList Info = new ArrayList();
        public static String API_URL = "http://whatshorrible.com/cache/";
        public static Splash splash;
        public static Boolean Good2Go = false;
        public static int progress = 0;
        public static string status = "";
        public static String response = String.Empty;
        public static String[] ipaddress = 
        { "whatshorrible.com", "jaredt.gotdns.com", };

        public static String RunningDirectory()
        {
            String _Path = Directory.GetCurrentDirectory() + "/Config.ini";
            String Path = new IniFile(_Path).IniReadValue("Path", "Path");

            if (!String.IsNullOrEmpty(Path)) return Path;
            else return Directory.GetCurrentDirectory();
        }

        public static String ParseName(String FileName)
        {
            string regex = "\\s*?(?:\\(.*?\\)|\\[.*?\\]|\\{.*?\\})";
            string Name = Regex.Replace((string)FileName, regex, "").Replace("_", " ");
            Name = Name.Split('.')[0].Split('-')[Name.Split('-').Length - 2];

            return Name.Trim();
        }

        public static String Synopsis(String FileName)
        {
            String Info = "";
            String Name = ParseName(FileName);
            String _Path = Directory.GetCurrentDirectory() + "/Cache/" + Name.Replace("?", " ") + ".wh";
            var sf = new StreamReader(File.Open(_Path, FileMode.OpenOrCreate));
            Info = sf.ReadToEnd(); sf.Close();
            
            if (Info == "")
            {
                XmlDocument doc = new XmlDocument();
                string BaseUrl = API_URL + Name.Replace('?', ' ').Replace(",", "") + ".xml";
                CredentialCache credCache = new CredentialCache();
                WebRequest request = HttpWebRequest.Create(BaseUrl);
                WebResponse response = request.GetResponse();
                doc.Load(response.GetResponseStream());
                Info = doc.GetElementsByTagName("synopsis")[0].InnerText.Replace("<br />", Environment.NewLine);
                while (new FileInfo(_Path).Length <= 0) File.WriteAllBytes(_Path, Encoding.ASCII.GetBytes(Info));
            }
            return Info;
        }

        public static String PosterImage(String FileName)
        {
            String imageURL = "";
            String Name = ParseName(FileName);
            String _Path = Directory.GetCurrentDirectory() + "/Config.ini";
            imageURL = new IniFile(_Path).IniReadValue("Images", Name);

            if (imageURL == "")
            {
                XmlDocument doc = new XmlDocument();
                string BaseUrl = API_URL + Name.Replace("?", " ").Replace(",", "") + ".xml";
                CredentialCache credCache = new CredentialCache();
                WebRequest request = HttpWebRequest.Create(BaseUrl);
                WebResponse response = request.GetResponse();
                doc.Load(response.GetResponseStream());
                imageURL = doc.GetElementsByTagName("image")[0].InnerText;
                imageURL = API_URL + imageURL.Split('/')[imageURL.Split('/').Length - 1];

                new IniFile(_Path).IniWriteValue("Images", Name, imageURL);
            }

            return imageURL;
        }
    }

    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// INIFile Constructor.
        /// </summary>
        /// <PARAM name="INIPath"></PARAM>
        public IniFile(string INIPath)
        {
            path = INIPath;
        }
        /// <summary>
        /// Write Data to the INI File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// Section name
        /// <PARAM name="Key"></PARAM>
        /// Key Name
        /// <PARAM name="Value"></PARAM>
        /// Value Name
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }
        /// <summary>
        /// Read Data Value From the Ini File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// <PARAM name="Key"></PARAM>
        /// <PARAM name="Path"></PARAM>
        /// <returns></returns>
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
            return temp.ToString();
        }
    }
}
